using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace PodInvaders
{
	public class InputPersistence
	{
		public static void SaveUserInput(ComboBox list, string Key)
		{
			string path = PathFromKey(Key);

			if (Regex.IsMatch(list.Text, @"^\s*$"))
				return;

			StringBuilder file = new StringBuilder();
			string line;

			if (!list.Items.Contains(list.Text))
				list.Items.Insert(0, list.Text);

			if (File.Exists(path))
			{
				StreamReader reader = new StreamReader(path);

				while (!reader.EndOfStream)
				{
					line = reader.ReadLine().Trim();
					if (line != "" && line != list.Text)
						file.Append("\r\n" + line);
				}
				reader.Close();
			}

			EnsureDirectory(path);

			StreamWriter writer = new StreamWriter(path);

			writer.Write(list.Text);
			if (file.ToString().Trim() != "")
				writer.Write(file);
			writer.Close();
		}

		public static void LoadUserInput(ComboBox list, string Key)
		{
			string line;
			string path = PathFromKey(Key);

			if (! File.Exists(path)) return;

			StreamReader reader = new StreamReader(path);

			while ((line = reader.ReadLine()) != null)
				list.Items.Add(line);

			reader.Close();
		}

		public static void EnsureDirectory(string path)
		{
			if (!Directory.Exists(Directory.GetParent(path).FullName))
				Directory.CreateDirectory(Directory.GetParent(path).FullName);
		}

		private static string PathFromKey(string Key)
		{
			string path =
				Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName, Key) + ".txt";

			return path;
		}
	}
}